package com.share.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.device.domain.*;
import com.share.device.mapper.CabinetMapper;
import com.share.device.mapper.CabinetSlotMapper;
import com.share.device.mapper.CabinetTypeMapper;
import com.share.device.service.ICabinetService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CabinetServiceImpl extends ServiceImpl<CabinetMapper, Cabinet> implements ICabinetService {

    private final CabinetMapper cabinetMapper;
    private final CabinetSlotMapper cabinetSlotMapper;
    private final PowerBankServiceImpl powerBankService;
    private final CabinetTypeMapper cabinetTypeMapper;

    /**
     * 查询充电宝柜机列表
     *
     * @param cabinet 充电宝柜机
     * @return 充电宝柜机集合
     */
    @Override
    public List<Cabinet> selectListCabinet(Cabinet cabinet) {
        return cabinetMapper.selectListCabinet(cabinet);
    }

    //未使用柜机
    @Override
    public List<Cabinet> searchNoUseList(String keyword) {
        LambdaQueryWrapper<Cabinet> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Cabinet::getCabinetNo, keyword);
        wrapper.eq(Cabinet::getStatus, 0);
        return cabinetMapper.selectList(wrapper);
    }

    @Override
    public Cabinet getBtCabinetNo(String cabinetNo) {
        return cabinetMapper.selectOne(new LambdaQueryWrapper<Cabinet>().eq(Cabinet::getCabinetNo, cabinetNo));
    }

    @Override
    public Map<String, Object> getAllInfo(Long id) {
        // 查询柜机信息
        Cabinet cabinet = this.getById(id);

        // 查询插槽信息
        List<CabinetSlot> cabinetSlotList = cabinetSlotMapper.selectList(new LambdaQueryWrapper<CabinetSlot>().eq(CabinetSlot::getCabinetId, cabinet.getId()));
        // 获取可用充电宝id列表
        List<Long> powerBankIdList = cabinetSlotList.stream().map(CabinetSlot::getPowerBankId).filter(Objects::nonNull).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(powerBankIdList)) {
            List<PowerBank> powerBankList = powerBankService.listByIds(powerBankIdList);
            Map<Long, PowerBank> powerBankIdToPowerBankMap = powerBankList.stream()
                    .collect(
                            Collectors.toMap(PowerBank::getId, PowerBank -> PowerBank)
                    );
            cabinetSlotList.forEach(item -> item.setPowerBank(
                    powerBankIdToPowerBankMap.get(item.getPowerBankId())
            ));
        }

        return Map.of("cabinet", cabinet, "cabinetSlotList", cabinetSlotList);
    }

    /* 新增方法供html页面查询 */
    @Override
    public CabinetVo getCabinetWithSlots(Long id) {
        Cabinet cabinet = this.getById(id);
        if (cabinet == null) return null;

        List<CabinetSlot> slots = cabinetSlotMapper.selectList(
                new QueryWrapper<CabinetSlot>()
                        .eq("cabinet_id", id)
                        .eq("del_flag", "0")
        );

        CabinetVo vo = new CabinetVo();
        vo.setId(cabinet.getId());
        vo.setName(cabinet.getName());
        vo.setCabinetNo(cabinet.getCabinetNo());
        vo.setClientId(cabinet.getClientId());
        vo.setTotalSlots(cabinet.getTotalSlots());

        int available = 0, occupied = 0, empty = 0;
        List<SlotVo> slotVos = new ArrayList<>();
        for (CabinetSlot s : slots) {
            SlotVo slotVo = new SlotVo();
            slotVo.setId(s.getSlotNo());
            slotVo.setPowerBankId(s.getPowerBankId());

            if ("0".equals(s.getStatus())) {
                slotVo.setStatus("available");
                available++;
            } else if ("1".equals(s.getStatus())) {
                slotVo.setStatus("occupied");
                occupied++;
            } else {
                slotVo.setStatus("empty");
                empty++;
            }
            slotVos.add(slotVo);
        }

        vo.setAvailableSlots(available);
        vo.setOccupiedSlots(occupied);
        vo.setEmptySlots(empty);
        vo.setSlots(slotVos);

        return vo;
    }

    @Override
    public CabinetVo updateSlotStatus(Long cabinetId, String slotNo, String action) {
        CabinetSlot slot = cabinetSlotMapper.selectOne(
                new QueryWrapper<CabinetSlot>()
                        .eq("cabinet_id", cabinetId)
                        .eq("slot_no", slotNo)
        );
        if (slot == null) return null;

        if ("rent".equals(action)) {
            slot.setStatus("1"); // 占用
        } else if ("return".equals(action)) {
            slot.setStatus("0"); // 空闲
            slot.setPowerBankId(null); // 归还时充电宝出库
        }
        System.err.println("slot: " + slot);
        cabinetSlotMapper.updateById(slot);

        return getCabinetWithSlots(cabinetId);
    }

    @Override
    public CabinetSlot getAvailableSlot(Long cabinetId) {
        return cabinetSlotMapper.selectOne(
                new QueryWrapper<CabinetSlot>()
                        .eq("cabinet_id", cabinetId)
                        .eq("status", "0")
                        .last("limit 1")
        );
    }

    @Override
    public List<CabinetSlot> getOccupiedSlots(Long cabinetId) {
        return cabinetSlotMapper.selectList(
                new QueryWrapper<CabinetSlot>()
                        .eq("cabinet_id", cabinetId)
                        .eq("status", "1")
        );
    }

    /**
     * 获取所有柜机列表
     */
    @Override
    public List<CabinetVo> getAllCabinets() {
        // 查询所有未删除的柜机
        List<Cabinet> cabinets = cabinetMapper.selectList(
                new QueryWrapper<Cabinet>().eq("del_flag", "0")
        );

        if (CollectionUtils.isEmpty(cabinets)) {
            return new ArrayList<>();
        }

        // 转换成 CabinetVo 只包含基本信息

        return cabinets.stream().map(c -> {
            CabinetVo vo = new CabinetVo();
            vo.setId(c.getId());
            vo.setName(c.getName());
            vo.setCabinetNo(c.getCabinetNo());
            vo.setClientId(c.getClientId());
            vo.setTotalSlots(c.getTotalSlots());
            // 不查询槽位详情，前端获取列表只需展示基本信息
            return vo;
        }).collect(Collectors.toList());
    }

    /**
     * 新增柜机
     */
    @Override
    public boolean addCabinet(Cabinet cabinet) {
        if (cabinet == null || cabinet.getCabinetTypeId() == null) {
            return false;
        }
        Integer slotNum = cabinetTypeMapper.getSlotNum(cabinet.getCabinetTypeId());

        cabinet.setTotalSlots(slotNum); // 设置总插槽数
        cabinet.setFreeSlots(slotNum); // 设置可用插槽数

        return save(cabinet);
    }
}
